package com.zjz.servlet.user;

import com.zjz.pojo.User;
import com.zjz.service.user.UserService;
import com.zjz.service.user.UserServiceImpl;
import com.zjz.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    //Servlet:控制层，调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("---" +"\n"+ "----LoginServlet---start"+"\n" +"--------------");
        //获取用户的用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //和用户数据库中的密码对比，调用业务层
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//登录的人查出来

        System.out.println("密码：" + user.getUserPassword());
        if(user != null&&(user.getUserPassword().equals(userPassword))){//查到有这个人
            //将用户的信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {//查无此人
            //转发回登录页面，并提示错误
            req.setAttribute("error","用户名，密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
